import styles from './index.module.scss';
import Icon from '@/components/Icon';
import NavBar from '@/components/NavBar';
import { useEffect,useRef, useState  } from 'react'
import { useDispatch } from 'react-redux'
import { getArticleDetail } from '@/store/action/article'
import { useParams } from 'react-router'
// import { RootState } from '@/store'
import { useAppSelector } from '@/store'
import DOMPurify from 'dompurify';
import dayjs from 'dayjs'
import Skeleton from '@/components/Skeleton';
import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'
import ArticleFooter from '@/components/ArticleFooter';
import NoComment from '@/components/NoComment';
import CommentItem from '@/components/Commentltem';
import { getComments } from '@/store/action/comment'
import Share from '@/components/Share';
import { Popup,Toast  } from 'antd-mobile';
import { changeUserFollowings } from '@/store/action/user';
import classNames from 'classnames';
import CommentInput from '@/components/CommentInput';
export default function Article() {
   // 添加评论的显示和隐藏
   const [showComment, setShowComment] = useState(false);
   const closeComment = () => {
     setShowComment(false);
   };
   // 关注功能
   const handleFollow = async () => {
    console.log(detail.art_id);

    await dispatch(changeUserFollowings(detail.art_id));
    Toast.show({
      content: detail.is_followed ? '已取消关注' : '关注成功',
      maskClickable: false,
      duration: 1000,
    });
  };
    // 分享功能
    const [share, setShare] = useState(false);
    const onCloseShare = () => {
      setShare(false);
    };
  const dispatch = useDispatch()
   // 准备开关变量，用于切换是否滚动到评论区
   const isShowComment = useRef(false)
    // 🔔 useParams 函数需要指定泛型确定 params 对象的格式
    const { detail } = useAppSelector((state) => state.article)
    const { comments } = useAppSelector((state) => state.comment)
    const params = useParams<{ id: string }>();
     // 作者信息 DOM
    const [showAuthor, setShowAuthor] = useState(false)   
 // 作者信息 DOM
 const authorRef = useRef<HTMLDivElement>(null);
 // 滚动容器
 const wrapperRef = useRef<HTMLDivElement>(null);

 const commemtHeadRef = useRef<HTMLDivElement>(null);

 const onShowComment = () => {
  isShowComment.current = !isShowComment.current
  console.log(isShowComment.current);
  
   // 计算评论区的距离
   const top = commemtHeadRef.current!.offsetTop - commemtHeadRef.current!.offsetHeight
   wrapperRef.current?.scrollTo({
     // 🧐 如果还没滚动到评论区的距离，点击直达评论区，否则返回到顶部
     top: isShowComment.current ? top : 0,
   })
 };

    useEffect(() => {
      // 获取文章的详情
      dispatch(getArticleDetail(params.id));
    //       // 获取文章的评论列表
    dispatch(getComments({ source: params.id }))
    }, [dispatch, params.id]);
    useEffect(() => {
      // 文章还没加载完毕，先不处理
      if (!detail.art_id) return
      // console.log('加载完毕了，需要高亮处理', detail.art_id)
      // 配置 highlight.js
      hljs.configure({
        // 忽略未经转义的 HTML 字符
        ignoreUnescapedHTML: true,
      })
  
      // 查找容器元素下符合 pre code 选择器规则的子元素，进行高亮
      const codes = document.querySelectorAll('.dg-html pre')
      if (codes.length > 0) {
        return codes.forEach((el: any) => hljs.highlightElement(el))
      }
    }, [detail.art_id])
    useEffect(() => {
      // 文章还没加载完毕，先不处理
      if (!detail.art_id) return;
  
      // 滚动事件处理函数 - 由于卸载组件的时候还需要用到，所以需要抽离出来写
      const scrollFn = () => {
        if (authorRef.current!.getBoundingClientRect().y < 0) {
          console.log('滚动出去可视区外了');
          setShowAuthor(true)
        }else{
          setShowAuthor(false)
        }
      };
      // 滚动容器绑定滚动事件
      wrapperRef.current?.addEventListener('scroll', scrollFn);
    }, [detail.art_id]);
  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        {/* 顶部导航栏 */}
        <NavBar    
         right={<Icon type="icongengduo"  onClick={() => setShare(true)} />}
          title={
            showAuthor ? (
              <div className="nav-author">
                <img src={detail.aut_photo} alt="" />
                <span className="name">{detail.aut_name}</span>
                <span
                  className={classNames(
                    'follow',
                    detail.is_followed ? 'followed' : ''
                  )}
                  onClick={handleFollow}
                >
                  {detail.is_followed ? '已关注' : '关注'}
                </span>
              </div>
            ) : (
              '文章详情'
            )
          }>文章详情</NavBar>
        <div className="wrapper">
          <div className="article-wrapper" hidden={!!detail.art_id}>
                   {/* 骨架屏占位效果 */}
                   <Skeleton />
          </div>
          <div className='article-wrapper' hidden={!detail.art_id}>
            {/* 文章描述信息栏 */}
            <div className="header">
              <h1 className="title">{detail.title}</h1>

              <div className="info">
                <span>{dayjs(detail.pubdate).format('YYYY-MM-DD hh:mm:ss')}</span>
                <span>{10} 阅读</span>
                <span>{detail.comm_count} 评论</span>
              </div>

              <div className="author" ref={authorRef}>
              <img src={detail.aut_photo} alt='' />
                <span className='name'>{detail.aut_name}</span>
                <span
                  className={classNames(
                    'follow',
                    detail.is_followed ? 'followed' : ''
                  )}
                  onClick={handleFollow}
                >
                  {detail.is_followed ? '已关注' : '关注'}
                </span>
              </div>
            </div>

            {/* 文章正文内容区域 */}
            <div className="content">
            <div
                className='content-html dg-html'
                // 💥 dompurify.sanitize() 对 HTML 内容进行净化，防止 XSS 攻击
                // dangerouslySetInnerHTML={{ __html: sanitize(detail.content) }}
                dangerouslySetInnerHTML={{
                  __html: DOMPurify.sanitize(detail.content || ''),
                }}
              />
              <div className='date'>
                发布文章时间：{dayjs(detail.pubdate).format('YYYY-MM-DD hh:mm:ss')}
              </div>
            </div>
            <div className="divider"></div>
            <div className="comment">
              {/* 评论总览信息 */}
              <div className="comment-header"  ref={commemtHeadRef}>
                <span>全部评论（{detail.comm_count}）</span>
                <span>{detail.like_count} 点赞</span>
              </div>
              {/* 评论列表 */}
              {comments.results?.length === 0 ? (
                <NoComment />
              ) : (
                comments.results?.map((item) => <CommentItem key={item.com_id} comment={item} />)
              )}
            </div>
          </div>
        </div>
         {/* 文章底部 */}
         <ArticleFooter
          onShowComment={onShowComment}
          onShare={() => setShare(true)}
          onComment={() => setShowComment(true)}
        />
        {/* 分享抽屉 */}
        <Popup
          position="bottom"
          bodyStyle={{ backgroundColor: 'transparent' }}
          visible={share}
          onMaskClick={onCloseShare}
        >
          <Share onClose={onCloseShare} />
        </Popup>
         {/* 评论抽屉 */}
         <Popup
          className="drawer"
          position="bottom"
          visible={showComment}
          onMaskClick={closeComment}
        >
          {showComment && <CommentInput onClose={closeComment} />}
        </Popup>
      </div>
    </div>
  );
}